<template>
  <!-- 外层容器：实现整体居中 -->
  <div class="page-container">
    <div class="form-container">
      <el-form ref="formRef" :model="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- 标题 -->
        <el-form-item label="标题" prop="title" :rules="[
          { required: true, message: '标题不能为空' },
        ]">
          <el-input v-model="ruleForm.title" type="text" autocomplete="off" maxlength="100" show-word-limit />
        </el-form-item>


        <el-form-item label="封面和摘要" prop="coverAndAbstract" :rules="[
          { required: true, message: '封面和摘要不能为空' },
        ]">
          <div class="cover-abstract-container">
            <Cover class="cover-component" @update:coverFile="val => ruleForm.coverFile = val" />
            <el-input v-model="ruleForm.coverAndAbstract" type="textarea" autocomplete="off" class="abstract-input" />
          </div>
        </el-form-item>


        <el-form-item label="*发送时间" prop="publishTime" class="time-picker-item">
          <div class="time-select-container">
            <el-radio-group v-model="ruleForm.publishTime">
              <el-radio label="immediate">立即发布</el-radio>
              <el-radio label="wait" class="ml-4">定时发布</el-radio>
            </el-radio-group>
            <PublishTime v-if="ruleForm.publishTime === 'wait'" class="publish-time-picker"
              @update:publishTime="val => ruleForm.scheduledTime = val" />
          </div>
        </el-form-item>


        <el-form-item class="button-group">

          <el-button @click="handleBack">上一步</el-button>
          <el-button type="primary" @click="submitForm(formRef)">发布</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>

import { reactive, ref, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { publishReleaseList } from '@/Api/newsApi'
import { useRouter } from 'vue-router'
import Cover from './Cover.vue'
import PublishTime from './publishTime.vue'
const publishList = ref([])
const ruleForm = reactive({
  title: '',
  coverAndAbstract: '',
  publishTime: 'immediate',
  scheduledTime: null, // 新增：用于存储定时发布的时间
  coverImage: '', // 新增：用于存储封面图片URL
  coverFile: null, // 新增：用于存储封面图片文件数据（Base64格式）
})

const formRef = ref<FormInstance>()

const props = defineProps({
  currentStep: {
    type: Number,
    required: true
  }
});

const emit = defineEmits(['update:currentStep']);
const router = useRouter();

// 暴露方法给父组件使用
defineExpose({
  getFormData: () => {
    return {
      title: ruleForm.title,
      coverAndAbstract: ruleForm.coverAndAbstract,
      coverFile: ruleForm.coverFile,
      publishTime: ruleForm.publishTime,
      ...(ruleForm.publishTime === 'wait' && { scheduledTime: ruleForm.scheduledTime })
    };
  }
});

// 监听表单数据变化，实时保存到sessionStorage
watch(
  () => ({
    title: ruleForm.title,
    coverAndAbstract: ruleForm.coverAndAbstract,
    coverFile: ruleForm.coverFile,
    publishTime: ruleForm.publishTime,
    scheduledTime: ruleForm.scheduledTime
  }),
  (newVal) => {
    sessionStorage.setItem('tempFormData', JSON.stringify(newVal));
  },
  { deep: true }
);

// 组件挂载时，尝试从sessionStorage恢复数据
const restoreFormData = () => {
  try {
    const savedData = sessionStorage.getItem('tempFormData');
    if (savedData) {
      const parsedData = JSON.parse(savedData);
      Object.assign(ruleForm, parsedData);
    }
  } catch (error) {
    console.error('恢复表单数据失败', error);
  }
};

restoreFormData();
const handleBack = () => {
  emit('update:currentStep', 1); // 触发事件，传递目标步骤值
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        const formData = {
          title: ruleForm.title,
          coverAndAbstract: ruleForm.coverAndAbstract,
          ...(ruleForm.coverFile && { coverFile: ruleForm.coverFile }),
          publishTime: ruleForm.publishTime,
          ...(ruleForm.publishTime === 'wait' && { scheduledTime: ruleForm.scheduledTime })
        };
        console.log('提交的完整数据:', formData);

        // 调用publishReleaseList接口获取最新发布列表
        const params = {
          issueNo: "",
          current: 1,
          currentSize: 10,
          waitPubTime: ruleForm.publishTime === 'wait' ? ruleForm.scheduledTime : null,
          issueTitle: ruleForm.title,
          issueCoverImage: ruleForm.coverFile.data,
          issueDescription: ruleForm.coverAndAbstract,
          issuePublishTime: ruleForm.publishTime === 'wait' ? ruleForm.scheduledTime : new Date().toISOString(),
          issuePublisher: "admin"
        };


        const response = await publishReleaseList(params);
        if (response && response.code === 200) {
          publishList.value = response.data.records || [];
          sessionStorage.setItem('publishNewsList', JSON.stringify(publishList.value));
          console.log('获取已发布新闻列表成功:', publishList.value);
        } else {
          console.error('获取已发布新闻列表失败', response);
        }

        // 提交成功后跳转到已发布页面
        router.push({ name: 'published' });
      } catch (error) {
        console.error('发布新闻时发生错误:', error);
        // 这里可以添加错误提示，例如使用Element Plus的ElMessage
      }
    } else {
      console.log('表单验证失败!')
    }
  })
}

</script>

<style scoped>
.page-container {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  padding: 30px;
}

.form-container {
  width: 100%;
  max-width: 800px;
}

.cover-abstract-container {
  display: flex;
  width: 100%;
  gap: 20px;
}

.cover-component {
  width: 160px;
  /* 固定封面宽度 */
  height: 100px;
  /* 建议添加高度,与设计图"480*200"比例一致 */
  border: 1px dashed #ccc;
  /* 模拟设计图中的上传区域边框 */
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  /* 防止封面被压缩 */
}

.abstract-input {
  flex: 1;
}

/* 按钮组样式调整 */
.button-group {
  margin-top: 20px;
}

.button-group .el-form-item__content {
  display: flex;
  justify-content: center;
  /* 按钮组水平居中 */
  gap: 16px;
  width: 100%;
  /* 确保内容区域占满宽度 */
}

/* 定时发布选项间距 */
.ml-4 {
  margin-left: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.time-picker-item .el-form-item__content {
  display: flex;
  align-items: center;
  min-height: 40px;
  /* 固定最小高度，避免动态变化 */
}

.time-select-container {
  display: flex;
  align-items: center;
  /* 始终保持垂直居中 */
  width: 100%;
  gap: 16px;
  min-height: 40px;
  /* 增加最小高度，防止显示/隐藏时高度变化 */
}

.time-select-container .el-radio-group {
  display: flex;
  align-items: center;
  height: 100%;
  /* 让radio组占满容器高度 */
}

.publish-time-picker {
  flex: 1;
  /* 让日期选择器占据剩余空间 */
  min-width: 200px;
  /* 确保有足够宽度显示选择器 */
}

/* 调整响应式布局 */
@media (max-width: 768px) {
  .time-select-container {
    flex-direction: column;
    align-items: flex-start;
    /* 移动端左对齐 */
    gap: 8px;
  }

  .time-picker-item .el-form-item__content {
    align-items: flex-start;
    /* 移动端内容区域左对齐 */
  }
}
</style>